package com.linian.pushforcampus.controller;

import com.alibaba.fastjson.JSONObject;
import com.linian.pushforcampus.domain.CampusActivity;
import com.linian.pushforcampus.domain.Vip;
import com.linian.pushforcampus.service.PushingService;
import com.linian.pushforcampus.service.TaskService;
import com.linian.pushforcampus.service.VipService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Controller
@Slf4j
public class GrabController {

    @Autowired
    private VipService vipService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private PushingService pushingService;

    public void grabActApply(CampusActivity campusActivity) {
        String publishId = campusActivity.getPublishId();
        List<Vip> allVips = vipService.getAllVipsByStates();
        if(allVips.size() !=0){
            ExecutorService executorService = Executors.newFixedThreadPool(allVips.size());
            //获取allVips的数量，并创建同等数量的线程
            for (Vip vip : allVips) {
                executorService.submit(() -> {
                    for (int i = 0; i < 5; i++) {
                        try {
                            JSONObject jsonObject = taskService.postActApply(vip.getStudentId(), publishId, vip.getXIdToken());
                            if (jsonObject.getIntValue("code") == HttpStatus.SC_OK||(jsonObject.getString("msg").contains("已报名"))) {
                                pushingService.wxpushingmsgForAutoGrab(campusActivity, vip);
                                log.error(jsonObject.toJSONString() + vip.getUserName() + "+---->ok");
                                break;
                            } else {
                                log.error(jsonObject.toJSONString() + vip.getUserName() + "+---->error");
                            }
                        } catch (Exception e) {
                            log.error("Error!" + vip.getUserName(), e);
                        }
                    }
                });
            }
            executorService.shutdown();
        }
    }
}
